package me.numark.activities;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import me.numark.R;
import me.numark.fragments.AskLoginFragment;
import me.numark.model.News;
import me.numark.model.NewsResponse;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.ShareContentWebpage;
import me.numark.utils.SinaShareManager;
import me.numark.utils.Utils;
import me.numark.view.PopupMoreView;
import me.numark.view.TencentWebViewClient;

/**
 * Created by tian on 14/11/16:下午10:41.
 */
public class WebviewActivity extends BaseActivity implements View.OnClickListener, IUiListener {
    @Bind(R.id.web_root)
    LinearLayout root;
    @Bind(R.id.webview)
    WebView webview;

    @Bind(R.id.recommend)
    ImageView recommend;

    @Bind(R.id.total_share)
    TextView totalShare;


    public ArrayList<String> urlList = new ArrayList();
    public String url;
    public String title;
    public boolean isFromMain;
    public static final String FROM_MAIN = "mainactivity";
    public static final String EXTRA_URL = "url";
    public static final String EXTRA_NEWS = "news";
    public static final String EXTRA_TITLE = "title";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_webview;
        super.onCreate(savedInstanceState);
        url = getIntent().getStringExtra(EXTRA_URL);
        isFromMain = getIntent().getBooleanExtra(FROM_MAIN,false);
        if (TextUtils.isEmpty(url)){
            Toast.makeText(this,"获取链接失败",Toast.LENGTH_SHORT).show();
            finish();
        }
        if (!TextUtils.isEmpty(title)) {
            //titleTextView.setText(title);
        }

        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webview.setWebViewClient(new TencentWebViewClient(urlList));
        webview.setWebChromeClient(webChromeClient);
        recommend.setOnClickListener(this);
        totalShare.setOnClickListener(this);
        webview.loadUrl(url);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.recommend:
                if (!Global.isLoggedIn()) {
                    AskLoginFragment.show(this);
                    return;
                }
                //Intent intent = new Intent(WebviewActivity.this,MarkActivity.class);
                Intent intent = new Intent(WebviewActivity.this,PublishActivity.class);
                if (!TextUtils.isEmpty(title)){
                    intent.putExtra(EXTRA_TITLE,title);
                }
                intent.putExtra(Constants.EXTRA_URL,url);
                startActivity(intent);
                finish();
                break;
            case R.id.total_share:
                //TODO 分享
                showMore();
                break;

            case R.id.share_weixin:
                dismissShowMore();
                Utils.wechatShare(0, url, title, title, getNewsPic());
                break;
            case R.id.share_circle:
                dismissShowMore();
                Utils.wechatShare(1, url, title, title, getNewsPic());
                break;
            case R.id.share_qq: {
                dismissShowMore();
                Tencent mTencent = null;
                try {
                    mTencent = Tencent.createInstance(Constants.TencentAppId, this);
                } catch (Throwable e) {
                    e.printStackTrace();
                    return;
                }
                final Bundle params = new Bundle();
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY,title);
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);
                //TODO 需要小图标
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,NetworkConstants.NEWS_DEFAULT_URL );
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "怒马");
//                params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,  "其他附加功能");
                mTencent.shareToQQ(this, params, this);
            }
            break;
            case R.id.share_qzone: {
                dismissShowMore();
                Tencent mTencent = null;
                try {
                    mTencent = Tencent.createInstance(Constants.TencentAppId, this);
                } catch (Throwable e) {
                    e.printStackTrace();
                    return;
                }
                final Bundle params = new Bundle();
                params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
                params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
                params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY,  title);
                ArrayList<String> value = new ArrayList<>();
                //TODO 需要小图标
                value.add(NetworkConstants.NEWS_DEFAULT_URL);
                params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, value);
                params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL,url);
                // params.putString(QzoneShare.SHARE_TO_QQ_IMAGE_URL,mFeed.news.face_img);
                params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, "怒马");
//                params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,  "其他附加功能");
                mTencent.shareToQzone(this, params, this);
            }
            break;
            case R.id.share_weibo: {
                dismissShowMore();
                SinaShareManager manager = new SinaShareManager();
                manager.registSina(this);
                ShareContentWebpage webpage
                        = new ShareContentWebpage(title,"",url,getNewsPic());
                manager.shareWebPage(webpage,this);
            }
            break;
            case R.id.more_browser: {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(browserIntent);
                dismissShowMore();
            }
            break;
            case R.id.more_copy: {
                ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                clipboard.setPrimaryClip(ClipData.newPlainText("url", url));
                Utils.showToast(getString(R.string.already_copy_url));
                dismissShowMore();
            }
            break;
            default:
                break;
        }
    }

    public Bitmap getNewsPic() {
        ImageView imageView = new ImageView(this);
            Picasso.with(this).load(R.drawable.share_default)
                    .into(imageView);
        Drawable drawable = imageView.getDrawable();
        if (drawable != null){
            return Utils.drawableToBitmap(drawable);
        }else
        return null;
    }
    /*private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            webview.loadUrl(url);
            return true;
        }
    }*/

    PopupMoreView mPopupMoreView;

    public void dismissShowMore() {
        if (mPopupMoreView != null) {
            mPopupMoreView.dismiss();
            mPopupMoreView = null;
        }
    }

    public void showMore() {
        dismissShowMore();
        mPopupMoreView = new PopupMoreView(this);
        mPopupMoreView.noDisplayButton.setVisibility(View.GONE);
        mPopupMoreView.noWatchButton.setVisibility(View.GONE);
        mPopupMoreView.moreReport.setVisibility(View.GONE);
        mPopupMoreView.moreDelete.setVisibility(View.GONE);
        mPopupMoreView.shareCircle.setOnClickListener(this);
        mPopupMoreView.shareQQ.setOnClickListener(this);
        mPopupMoreView.shareQZone.setOnClickListener(this);
        mPopupMoreView.shareWeibo.setOnClickListener(this);
        mPopupMoreView.shareWeixin.setOnClickListener(this);
        mPopupMoreView.moreCopy.setOnClickListener(this);
        mPopupMoreView.moreBrowser.setOnClickListener(this);
        mPopupMoreView.show();
    }

    @Override
    public void onComplete(Object o) {

    }

    @Override
    public void onError(UiError uiError) {

    }

    @Override
    public void onCancel() {

    }


    WebChromeClient webChromeClient = new WebChromeClient(){
        @Override
        public void onReceivedTitle(WebView view, String t) {
            super.onReceivedTitle(view, t);
            if (t!=null){
                title = t;
                titleTextView.setText(title);
            }else {
                titleTextView.setText(getString(R.string.mark_url_preview));
            }

        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        // If it wasn't the Back key or there's no web page history, bubble up to the default
        // system behavior (probably exit the activity)
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onPause() {
        super.onPause();
        webview.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        webview.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        root.removeView(webview);
        webview.removeAllViews();
        webview.destroy();
    }
}
